package com.sea.base.ext.global

import androidx.core.widget.NestedScrollView
import com.sea.base.R
import com.sea.base.ext.view.getTypeTag
import java.util.LinkedList

@Deprecated("请使用addOnScrollChangeListener")
inline fun NestedScrollView.setOnScrollChangeListenerExt(
    crossinline listener: NestedScrollView.(scrollX: Int, scrollY: Int, oldScrollX: Int, oldScrollY: Int) -> Unit
): NestedScrollView.OnScrollChangeListener {
    val l = NestedScrollView.OnScrollChangeListener { _, scrollX, scrollY, oldScrollX, oldScrollY ->
        this.listener(scrollX, scrollY, oldScrollX, oldScrollY)
    }
    setOnScrollChangeListener(l)
    return l
}

/**
 * 拓展setOnScrollChangeListener，让它支持添加多个
 * 注意：会占用setOnScrollChangeListener，请不要私自调用setOnScrollChangeListener
 */
fun NestedScrollView.addOnScrollChangeListener(
    listener: NestedScrollView.(scrollX: Int, scrollY: Int, oldScrollX: Int, oldScrollY: Int) -> Unit
) {
    val singleListener = this.getTypeTag<SingleNestedScrollViewListener>(R.id.tag_nested_scroll_view_listener)
        ?: SingleNestedScrollViewListener().also {
            setOnScrollChangeListener(it)
            this.setTag(R.id.tag_nested_scroll_view_listener, it)
        }
    if (!singleListener.listeners.contains(listener)) {
        singleListener.listeners.add(listener)
    }
}

fun NestedScrollView.removeOnScrollChangeListener(
    listener: NestedScrollView.(scrollX: Int, scrollY: Int, oldScrollX: Int, oldScrollY: Int) -> Unit
) {
    this.getTypeTag<SingleNestedScrollViewListener>(R.id.tag_nested_scroll_view_listener)?.listeners?.remove(listener)
}

private class SingleNestedScrollViewListener : NestedScrollView.OnScrollChangeListener {
    val listeners = LinkedList<NestedScrollView.(scrollX: Int, scrollY: Int, oldScrollX: Int, oldScrollY: Int) -> Unit>()
    override fun onScrollChange(v: NestedScrollView, scrollX: Int, scrollY: Int, oldScrollX: Int, oldScrollY: Int) {
        listeners.forEachReverseSequence { _, listener ->
            v.listener(scrollX, scrollY, oldScrollX, oldScrollY)
        }
    }
}